import turtle
import math
import time

# 初始化窗口
screen = turtle.Screen()
screen.setup(800, 800)
screen.title("鳄鱼追人模拟 - 动态逃生路径")
screen.tracer(0)  # 关闭自动刷新

# 初始化人类
human = turtle.Turtle()
human.shape("circle")
human.color("blue")
human.shapesize(0.8)
human.penup()
human.goto(0, 0)
human.pendown()

# 初始化三条鳄鱼
crocodiles = []
colors = ["red", "green", "orange"]
positions = [(-300, 300), (300, 300), (0, -300)]  # 三个方位
speeds = [20, 20, 15]  # 对应速度

for i in range(3):
    croc = turtle.Turtle()
    croc.shape("turtle")
    croc.color(colors[i])
    croc.shapesize(1.2)
    croc.penup()
    croc.goto(positions[i])
    croc.pendown()
    crocodiles.append(croc)

# 速度参数
human_speed = 10
time_step = 0.05  # 更小的时间步长用于平滑动画
start_time = time.time()


def calculate_best_direction():
    """计算最优逃生方向（向量标准化）"""
    escape_vector = [0.0, 0.0]
    human_pos = human.pos()

    for i, croc in enumerate(crocodiles):
        # 获取鳄鱼位置和速度
        croc_pos = croc.pos()
        croc_speed = speeds[i]

        # 计算相对位置向量
        dx = human_pos[0] - croc_pos[0]
        dy = human_pos[1] - croc_pos[1]
        distance = math.hypot(dx, dy)

        if distance == 0:
            continue

        # 计算时间权重：鳄鱼到达时间 = 距离/（鳄鱼速度 - 人类速度分量）
        relative_speed = croc_speed - human_speed * (dx / distance)
        if relative_speed <= 0:
            weight = 0
        else:
            time_to_reach = distance / relative_speed
            weight = 1 / (time_to_reach ** 2)  # 时间越短权重越大

        # 累加逃生向量
        escape_vector[0] += dx * weight
        escape_vector[1] += dy * weight

    # 归一化向量
    vec_length = math.hypot(escape_vector[0], escape_vector[1])
    if vec_length == 0:
        return 0, 1  # 默认向上移动
    return (escape_vector[0] / vec_length, escape_vector[1] / vec_length)


def update_positions():
    """更新所有角色位置"""
    # 计算人类移动方向
    direction = calculate_best_direction()
    human.setheading(math.degrees(math.atan2(direction[1], direction[0])))
    human.forward(human_speed * time_step)

    # 更新鳄鱼位置
    human_pos = human.pos()
    for i, croc in enumerate(crocodiles):
        # 计算指向人类的向量
        dx = human_pos[0] - croc.xcor()
        dy = human_pos[1] - croc.ycor()
        angle = math.degrees(math.atan2(dy, dx))

        # 设置方向并移动
        croc.setheading(angle)
        croc.forward(speeds[i] * time_step)

    # 实时更新画面
    screen.update()


# 主循环
while True:
    # 碰撞检测
    for croc in crocodiles:
        if croc.distance(human) < 15:
            # 显示存活时间
            survival_time = time.time() - start_time
            human.penup()
            human.goto(0, 0)
            human.write(f"存活时间: {survival_time:.2f}秒",
                        align="center", font=("Arial", 24, "bold"))
            turtle.done()
            exit()

    # 更新位置并保持循环
    update_positions()
    time.sleep(time_step)